﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using memcached;

namespace CacheExamples
{
    public static class PerfTest
    {
        private static byte[] data = new byte[4096];
        
        public static void RunTest()
        {
            int max = 500;
            using (new PerformanceWrapper("PerfTesting"))
            using (var v = new MemCache())
            {
                v.Set("test2", "0");
                long val1 = v.Increment("test2", 1);
                System.Diagnostics.Debug.Assert(val1 == 1);

                PerfTestRun(max, "Increment", () =>
                {
                    long val = v.Increment("test2", 1);//<0.5ms
                });

                PerfTestRun(max, "Decrement", () =>
                {
                    long val = v.Decrement("test2");//<0.4ms
                });

                PerfTestRun(max, "Set s", () =>
                {
                    bool res = v.Set("test1", "test value");//<0.4ms
                });

                PerfTestRun(max, "Get s", () =>
                {
                    bool success;
                    string s = v.Get<string>("test1", out success);//<0.4ms
                });

                PerfTestRun(max, "Set 4K", () =>
                {
                    bool res = v.Set("test3", data);//<0.6ms
                });

                PerfTestRun(max, "Get 4K", () =>
                {
                    bool success;
                    byte[] d = v.Get<byte[]>("test3", out success);//<0.7ms
                });
            }
        }

        private static void PerfTestRun(int loops, string name, Action proc)
        {
            PerformanceTimer t = new PerformanceTimer();
            System.Threading.Thread.Sleep(500);
            t.Start();
            for (int i = 0; i < loops; i++)
                proc();
            t.Stop();
            System.Diagnostics.Trace.WriteLine(string.Format("{0}: {1}={2}s",
                name, t.Elapsed / loops, t.Seconds / loops));
        }
    }
}